package com.xukai.springboot.Initialization;

import com.xukai.springboot.entity.statistics.t_statis_datasource;
import com.xukai.springboot.quartzTask.QuartzTaskManager;
import com.xukai.springboot.quartzTask.UpdateStatisTask;
import com.xukai.springboot.service.statistics.DataCaptureService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class Initialization implements CommandLineRunner {
    private final Logger logger = LoggerFactory.getLogger(Initialization.class);


    /**
     * 数据抓取服务
     */
    @Autowired
    private DataCaptureService dataCaptureService;

    @Autowired
    private QuartzTaskManager quartzTaskManager;


    @Override
    public void run(String... args) throws Exception {
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>服务启动，执行数据初始化操作<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        // AnnoManageUtil.getApis("com.xukai.springboot.controller");
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>服务启动，统计数据源加载初始化操作开始<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

        //dataCaptureService.UpdateStatisData();
        InitTask(dataCaptureService.GetDataSourceList());

        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>服务启动，统计数据源加载初始化操作结束<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");


    }


    /**
     * 初始化数据源定时任务
     *
     * @param datasources
     */
    private void InitTask(List<t_statis_datasource> datasources) {
        try {
            if (datasources == null || datasources.size() == 0) {
                return;
            }
            for (t_statis_datasource item : datasources) {
                String taskName = String.valueOf(item.getId());
                String taskGroupName = String.valueOf(item.getId());
                String cron = item.getDataRefreshTime();
                quartzTaskManager.AddTask(taskName, taskGroupName, UpdateStatisTask.class, cron);
            }
        } catch (Exception ex) {
            logger.error("初始化数据源定时任务", ex);
        }
    }
}
